<?php
/**
 * Created by PhpStorm.
 * User: DongYao
 * Date: 2017/12/15
 * Time: 下午2:06
 */

function format_config_array($var, $level = 1)
{
    $blankspace = str_repeat(' ', $level * 4);
    $endblankspace = str_repeat(' ', ($level -1) * 4);

    if (is_array($var)) {
        $toImplode = array();
        $level++;
        foreach ($var as $key => $value) {
            $toImplode[] = var_export($key, true).' => '. format_config_array($value, $level);
        }
        $code = "[\r\n{$blankspace}" . implode(",\r\n{$blankspace}", $toImplode) . "\r\n{$endblankspace}]";
        return $code;
    } else {
        if (is_float($var)) {
            return $var;
        }

        if (is_string($var) && in_array($var, ['true', 'false'])) {
            if ($var === 'true') {
                $var = true;
            } else if ($var === 'false') {
                $var = false;
            }
        }
        return var_export($var, true);
    }
}


if (! function_exists('udate')) {
    /**
     * Generate the URL to a named route.
     *
     * @param string $format
     * @param null $utimestamp
     * @return string
     * @internal param string $name
     * @internal param array $parameters
     * @internal param bool $absolute
     */
    function udate($format = 'u', $utimestamp = null) {
        if (is_null($utimestamp))
            $utimestamp = microtime(true);

        $timestamp = floor($utimestamp);
        $milliseconds = round(($utimestamp - $timestamp) * 1000000);

        return date(preg_replace('`(?<!\\\\)u`', $milliseconds, $format), $timestamp);
    }
}


if (! function_exists('chmodr')) {
    /**
     * @param $path
     * @param $filemode
     * @return bool
     */
    function chmodr($path, $filemode) {
        if (!is_dir($path))
            return chmod($path, $filemode);
        $dh = opendir($path);
        while (($file = readdir($dh)) !== false) {
            if($file != '.' && $file != '..') {
                $fullpath = $path.'/'.$file;
                if(is_link($fullpath))
                    return FALSE;
                elseif(!is_dir($fullpath) && !chmod($fullpath, $filemode))
                    return FALSE;
                elseif(!chmodr($fullpath, $filemode))
                    return FALSE;
            }
        }
        closedir($dh);
        if(chmod($path, $filemode))
            return TRUE;
        else
            return FALSE;
    }
}

if (! function_exists('v_route')) {
    /**
     * Generate the URL to a named route.
     *
     * @param  string  $name
     * @param  array   $parameters
     * @param  bool    $absolute
     * @return string
     */
    function v_route($name, $parameters = [], $absolute = true)
    {
        try {
            return app('url')->route($name, $parameters, $absolute);
        } catch (Exception $e) {

        }

        return '#';
    }
}

if (! function_exists('v_route_uri')) {
    /**
     * 获取原始路由的URI地址
     * @param  [type] $name [description]
     * @return [type]       [description]
     */
    function v_route_uri($name)
    {
        try {
            $router = app('router')->getRoutes()->getByName($name);
            if ($router) {
                return $router->uri();
            }
        } catch (Exception $e) {

        }
        return '';
    }
}

if (! function_exists('is_true')) {
    /**
     * 判断是否是TRUE or FALSE
     * @param  [type]  $val         [description]
     * @param  boolean $return_null [description]
     * @return boolean              [description]
     */
    function is_true($val, $return_null = false)
    {
        $boolval = ( is_string($val) ? filter_var($val, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) : (bool) $val );
        return ( $boolval===null && !$return_null ? false : $boolval );
    }
}

if (!function_exists('device_qrcode_image')) {
    /**
     * 保存二维码并获取地址
     * @param $device_sn
     * @param int $size
     * @return mixed
     */
    function device_qrcode_image($device_sn, $size = 800)
    {
        $base_dir = storage_path('app/device/qrcodes/');

        if (!file_exists($base_dir)) {
            Storage::makeDirectory('device/qrcodes/');
        }

        $file_path = $base_dir . "{$device_sn}.png";
        if (file_exists($file_path)) {
            @unlink($file_path);
        }

        $qrcode = QrCode::format('png')->size($size)
            ->margin(1);

        $logo_path = resource_path('assets/js/webapp/images/logo.jpg');
        if (file_exists($logo_path)) {
            $qrcode = $qrcode->merge($logo_path, 0.2, true);
        }

        $url = rtrim(env('APP_URL'), '/') . '/webapp/#/device/detail?device_sn=' . $device_sn;
        $qrcode->errorCorrection('M')
            ->generate($url, $file_path);

        return $file_path;
    }
}


if (!function_exists('device_qrcode_base64')) {
    /**
     * 获取设备消费的二维码base64格式
     * @param $device_sn
     * @param int $size
     * @return mixed
     */
    function device_qrcode_base64($device_sn, $size = 100)
    {
        $url = rtrim(env('APP_URL'), '/') . '/webapp/#/device/detail?device_sn=' . $device_sn;

        $qrcode = QrCode::format('png')->size($size);

        $logo_path = resource_path('assets/js/webapp/images/logo.jpg');
        if (file_exists($logo_path)) {
            $qrcode = $qrcode->merge($logo_path, 0.2, true);
        }

        return 'data:image/png;base64,' . base64_encode($qrcode->margin(1)->generate($url));
    }
}

if (!function_exists('get_baidu_point_for_ip')) {
    /**
     * 根据IP地址获取百度坐标地址
     * @param string $ip
     * @param string $coor
     * @param string $baidu_map_ak
     * @return mixed
     */
    function get_baidu_point_for_ip($ip = '', $baidu_map_ak = '', $coor = 'bd09ll')
    {
        if (empty($ip)) {
            $ip = app('request')->ip();
        }
        $api_url = "http://api.map.baidu.com/location/ip?ak={$baidu_map_ak}&ip={$ip}&coor={$coor}";

        $guzzle = new GuzzleHttp\Client;
        $response = $guzzle->post($api_url);

        $data = json_decode((string) $response->getBody(), true);

        if (isset($data['content']['point'])) {
            return [
                'lat' => $data['content']['point']['x'],
                'lng' => $data['content']['point']['y'],
            ];
        }

        return [
            'lat' => 0,
            'lng' => 0,
        ];
    }
}

/**
 * 获取充值金额赠送的积分数量
 * @param $money
 * @return int
 */
function find_charge_give_score($money)
{
    $charge_moneys = config('system.charge_moneys', []);

    foreach ($charge_moneys as $item) {
        if ($item['money'] == $money) {
            return $item['score'];
        }
    }

    return 0;
}